<template>
  <div>
    <!-- 卡片 -->
    <a-row :gutter="24" style="margin: 10px">
      <a-col :sm="6" class="padding-r-no" v-for="(card, index) in cardInfo" :key="index">
        <div class="card-inner">
          <div class="title">{{ card.title }}</div>
          <div class="subtitle">{{ card.subtitle }}</div>
          <div class="total" :style="{ color: card.color }">{{ topStatus[card.total] }}</div>
          <div class="progress">
            <a-progress :strokeColor="card.color" :percent="card.percent" :showInfo="false" />
          </div>
          <div v-if="card.showInfo" class="progress color-grey">
            <span>{{ l('progress') }}</span>
            <span>{{ card.percent }}%</span>
          </div>
        </div>
      </a-col>
    </a-row>
    <a-row :gutter="24" style="margin: 0 10px">
      <a-col :sm="12" class="padding-r-no">
        <div class="statistics">
          <!-- 统计头部 -->

          <div class="padding-bottom">
            <history-outlined class="color-red font-16" />
            <span class="title color-red"> {{ l('DailySales') }}</span>
          </div>
          <div class="statistics-body">
            <div v-if="dailySalesIsShow" style="height: 100%; width: 100%" ref="daily-chart"></div>

            <a-empty v-else :image="simpleImage" />
          </div>
        </div>
      </a-col>
      <a-col :sm="12" class="padding-r-no">
        <div class="statistics">
          <div class="padding-bottom">
            <span class="title color-blue"> {{ l('StatisticsData') }}</span>
          </div>
          <!-- 表格 -->
          <div>
            <a-table
              :dataSource="regionTableList"
              :columns="regionColumns"
              :pagination="false"
              :scroll="{ y: '200px' }"
              size="small"
              :rowSelection="{
                selectedRowKeys: selectedRowKeys,
                onChange: onSelectChange,
                getCheckboxProps: getCheckboxProps,
                checkAll: checkAll,
              }"
            >
              <template #bodyCell="{ column, record, index }">
                <template
                  v-if="
                    column.key === 'sales' ||
                    column.key === 'averagePrice' ||
                    column.key === 'totalPrice'
                  "
                >
                  US${{ record[column.key] }}
                </template>
                <template v-if="column.key === 'change'">
                  <div>
                    <div
                      style="height: 100%"
                      :id="'region-chart' + index"
                      :ref="'region-chart' + index"
                    ></div>
                  </div>
                </template>
              </template>
            </a-table>
          </div>
        </div>
      </a-col>
    </a-row>
    <a-row :gutter="24" style="margin: 0 10px">
      <a-col :sm="12" class="padding-r-no">
        <div class="statistics">
          <!-- 统计头部 -->
          <div class="flex-header">
            <div>
              <pie-chart-outlined class="color-green font-16" />
              <span class="title color-green"> {{ l('GeneralStatusData') }}</span>
            </div>
            <div>
              <a-button type="primary">
                <template #icon><redo-outlined /></template>
                {{ l('Refresh') }}
              </a-button>
            </div>
          </div>
          <!-- 统计主体 -->
          <div class="statistics-body">
            <div
              v-if="Object.keys(generalStatsData).length > 0"
              style="height: 100%; width: 100%"
              ref="general-chart"
            >
              <div
                v-for="(item, index) in generalOptionData"
                :key="index"
                style="height: 100%; width: 33.3%; display: inline-block"
                :ref="index + '-general'"
                :id="index + '-general'"
              ></div>
            </div>
            <a-empty v-else :image="simpleImage" />
          </div>
        </div>
      </a-col>
      <a-col :sm="12" class="padding-r-no">
        <div class="statistics">
          <div>
            <pie-chart-outlined class="color-blue font-16" />
            <span class="title color-green"> {{ l('MemberActivity') }} </span>
          </div>
          <!-- 表格 -->
          <div>
            <a-table
              :scroll="{ y: '200px' }"
              :dataSource="memberList"
              :columns="memberColumns"
              :pagination="false"
              size="small"
            />
          </div>
        </div>
      </a-col>
    </a-row>
  </div>
</template>

<script lang="ts">
  import { AppComponentBase } from '/@/shared/component-base';
  import { defineComponent } from 'vue';
  import { Empty } from 'ant-design-vue';
  import { PieChartOutlined, HistoryOutlined, RedoOutlined } from '@ant-design/icons-vue';
  import { Dayjs } from 'dayjs';
  import {
    GetGeneralStatsOutput,
    GetTopStatsOutput,
    MemberActivity,
    RegionalStatCountry,
    TenantDashboardServiceProxy,
  } from '/@/shared/service-proxies';
  import * as echarts from 'echarts'; //引入图表插件

  export default defineComponent({
    name: 'tenant-dashboard',
    mixins: [AppComponentBase],
    components: {
      PieChartOutlined,
      HistoryOutlined,
      RedoOutlined,
    },
    props: {
      startTime: {
        type: Dayjs,
      },
      endTime: {
        type: Dayjs,
      },
      rangePicker: {
        type: Array,
      },
    },
    data() {
      return {
        dataPicker: 'daily',
        simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
        tenantDashboardServiceProxy: new TenantDashboardServiceProxy(),
        impendingTenantsTotal: 10,
        memberList: [] as MemberActivity[],
        memberColumns: [
          { title: this.l('Name'), dataIndex: 'name', key: 'name' },
          { title: this.l('Earnings'), dataIndex: 'earnings', key: 'earnings' },
          { title: this.l('Cases'), dataIndex: 'cases', key: 'cases' },
          { title: this.l('Closed'), dataIndex: 'closed', key: 'closed' },
          { title: this.l('Rate'), dataIndex: 'rate', key: 'rate' },
        ],
        regionColumns: [
          { title: this.l('Country'), dataIndex: 'countryName', key: 'countryName' },
          { title: this.l('Sales'), dataIndex: 'sales', key: 'sales' },
          { title: this.l('Variety'), dataIndex: 'change', key: 'change' },
          { title: this.l('AveragePrice'), dataIndex: 'averagePrice', key: 'averagePrice' },
          { title: this.l('TotalPrice'), dataIndex: 'totalPrice', key: 'totalPrice' },
        ],
        cardInfo: [
          {
            title: this.l('TotalPrice'),
            subtitle: 'All Customs Value',
            total: 'totalProfit',
            percent: 100,
            color: '#1890ff',
            showInfo: false,
          },
          {
            title: this.l('NewFeedback'),
            subtitle: 'Customer Review',
            total: 'newFeedbacks',
            percent: 100,
            color: '#8950fc',
            showInfo: false,
          },
          {
            title: this.l('NewSubscription'),
            subtitle: 'Fresh Order Amount',
            total: 'newOrders',
            percent: 60,
            color: '#f64e60',
            showInfo: true,
          },
          {
            title: this.l('NewUser'),
            subtitle: 'Joined New User',
            total: 'newUsers',
            percent: 80,
            color: '#1bc5bd',
            showInfo: true,
          },
        ],
        topStatus: new GetTopStatsOutput(),
        dailySalesIsShow: false,
        dailyChartsOption: {
          xAxis: {
            show: false,
            type: 'category',
          },
          tooltip: {
            formatter: 'DAY{b}<br />{c0}',
            trigger: 'item',
          },
          yAxis: {
            show: false,
          },
          series: [
            {
              data: [] as number[],
              type: 'bar',
            },
          ],
          color: ['#34bfa3'],
        },
        regionTableList: [] as RegionalStatCountry[],
        generalStatsData: new GetGeneralStatsOutput(),
        generalOptionData: [],
      };
    },
    mounted() {
      this.getTopStatus();
      this.getDailySales();
      this.getRegionalStats();
      this.getGeneralStats();
      this.getMemberActivity();
    },
    methods: {
      /**
       * table默认配置 （是否禁用）
       */
      getCheckboxProps() {
        return {
          disabled: true,
        };
      },
      /** 获取头部数据 */
      getTopStatus(): void {
        this.tenantDashboardServiceProxy.getTopStats().then((res) => {
          this.topStatus = res;
        });
      },
      /** 每日销售额 */
      getDailySales() {
        this.tenantDashboardServiceProxy.getDailySales().then((res) => {
          if (res && res.dailySales && res.dailySales.length) {
            this.dailySalesIsShow = true;
            this.dailyChartsOption.series[0].data = res.dailySales as any;
            setTimeout(() => {
              echarts.init(this.$refs['daily-chart'] as any).setOption(this.dailyChartsOption); //配置项加载到表格中
            }, 50);
          } else {
            this.dailySalesIsShow = false;
          }
        });
      },
      /** 地区统计数据 */
      getRegionalStats() {
        this.tenantDashboardServiceProxy.getRegionalStats().then((res) => {
          this.regionTableList = res.stats as RegionalStatCountry[];
          const regionChartOptions = res.stats?.map((item) => {
            return {
              xAxis: {
                show: false,
                data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun', 'ds', 'dss', 'as'],
              },
              yAxis: {
                show: false,
                type: 'value',
              },
              series: [
                {
                  data: item.change,
                  type: 'line',
                  smooth: true,
                },
              ],
            };
          });

          setTimeout(() => {
            res.stats?.map((item, index) => {
              let myChart = echarts.init(document.getElementById(`region-chart${index}`) as any);

              myChart.setOption((regionChartOptions as any)[index]);
            });
          }, 100);
        });
      },
      //获取常规状态数据
      getGeneralStats() {
        this.tenantDashboardServiceProxy.getGeneralStats().then((res) => {
          this.generalStatsData = res;
          this.generalOptionData = [];
          let total = 0;
          for (let key in res) {
            this.generalOptionData.push({
              name: key,
              value: res[key],
            });
            total = total + res[key];
          }
          let otherOption = {
            tooltip: {
              trigger: 'item',
            },
          };
          let option = {
            title: this.generalOptionData.map((data) => {
              return {
                subtext: data.name + '\n' + ((data.value / total) * 100).toFixed(0) + '%',
                left: 'center',
                top: '40%',
              };
            }),
            series: this.generalOptionData.map((data, index) => {
              return {
                type: 'pie',
                radius: [70, 80],
                left: '35%',
                width: '33.33%',
                top: '10',
                itemStyle: {
                  borderColor: '#fff',
                  borderWidth: 1,
                },
                data: this.getChartData(this.generalOptionData, index),
                label: {
                  show: false,
                },
              };
            }),
          };

          setTimeout(() => {
            option.series.map((item, index) => {
              let myChart = echarts.init(document.getElementById(`${index}-general`) as any);
              myChart.setOption({ series: [item], title: option.title[index], ...otherOption });
              // echarts.init(this.$refs[`general-chart`] as any).setOption(option); //配置项加载到表格中
            });
          }, 50);
        });
      },
      getChartData(data, index) {
        let filter = [] as any;
        if (Array.isArray(data) && data.length > 0) {
          filter = data.filter((item, idx) => {
            return index !== idx;
          });
        }

        return [data[index], { name: '', value: filter[0].value + filter[1].value }];
      },
      /** 获取member */
      getMemberActivity() {
        this.tenantDashboardServiceProxy.getMemberActivity().then((res) => {
          this.memberList = res.memberActivities as MemberActivity[];
        });
      },
    },
  });
</script>

<style lang="less" scoped>
  @import './tenant-dashboard.less';
</style>
